import { defineComponent, ref, onMounted, onUnmounted, watch, createVNode } from 'vue';
import { CountUp } from './countUp.js';

/**
 *
 * @param props
 * @returns
 */
const index = /* @__PURE__ */ defineComponent({
  name: 'CountUp',
  props: {
    value: {
      type: [Number, String],
      default: 0
    },
    start: {
      type: Number,
      default: 0
    },
    duration: {
      type: Number,
      default: 2
    },
    decimal: {
      type: Number,
      default: 0
    },
    useGrouping: {
      type: Boolean,
      default: true
    },
    useEasing: {
      type: Boolean,
      default: true
    },
    separator: {
      type: String,
      default: ','
    },
    formattingFn: {
      type: Function
    },
    prefix: {
      type: String,
      default: ''
    },
    suffix: {
      type: String,
      default: ''
    }
  },
  emits: ['end'],
  setup(props, {
    emit,
    expose
  }) {
    const target = ref(null); // 目标 DOM 元素
    const instance = ref(null); // CountUp 实例

    // 初始化 CountUp 实例
    const initCountUp = () => {
      if (!target.value) return;
      console.log(111);
      const options = {
        startVal: props.start,
        duration: props.duration,
        decimalPlaces: props.decimal,
        useGrouping: props.useGrouping,
        useEasing: props.useEasing,
        separator: props.separator,
        formattingFn: props.formattingFn,
        prefix: props.prefix,
        suffix: props.suffix,
        onCompleteCallback: () => emit('end')
      };
      instance.value = new CountUp(target.value, parseFloat(props.value), options);
      if (instance.value.error) {
        console.error(instance.value.error);
      } else {
        instance.value.start();
      }
    };

    // 更新目标值
    const update = val => {
      instance.value?.update(val);
    };

    // 暂停/恢复动画
    const pauseResume = () => {
      instance.value?.pauseResume();
    };

    // 重置动画
    const reset = () => {
      instance.value?.reset();
    };
    const start = () => {
      instance.value?.start();
    };

    // 生命周期钩子
    onMounted(initCountUp);
    onUnmounted(() => {
      if (instance.value) {
        instance.value = null;
      }
    });

    // 监听 value 变化
    watch(() => props.value, val => {
      update(parseFloat(val));
    });

    // 暴露方法
    expose({
      reset,
      update,
      start,
      pauseResume
    });
    return () => createVNode("span", {
      "class": "cm-count-up",
      "ref": target
    }, null);
  }
});

export { index as default };
